package org.dromara.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.dromara.admin.domain.Company;
import org.dromara.admin.domain.Employee;
import org.dromara.admin.domain.vo.EmployeeVo;
import org.dromara.admin.service.IEmployeeService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.dromara.admin.domain.bo.CustomerBo;
import org.dromara.admin.domain.vo.CustomerVo;
import org.dromara.admin.domain.Customer;
import org.dromara.admin.mapper.CustomerMapper;
import org.dromara.admin.service.ICustomerService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 客户信息Service业务层处理
 *
 * @author Lion Li
 * @date 2025-10-10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class CustomerServiceImpl implements ICustomerService {

    private final CustomerMapper baseMapper;
    private final IEmployeeService employeeService;

    /**
     * 查询客户信息
     *
     * @param id 主键
     * @return 客户信息
     */
    @Override
    public CustomerVo queryById(Long id) {
        CustomerVo customerVo = baseMapper.selectVoById(id);
        if (BeanUtil.isEmpty(customerVo)) {
            throw new ServiceException("客户信息不存在！");
        }
        return customerVo;
    }

    /**
     * 分页查询客户信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 客户信息分页列表
     */
    @Override
    public TableDataInfo<CustomerVo> queryPageList(CustomerBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Customer> lqw = buildQueryWrapper(bo);
        Page<CustomerVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 分页查询当前登录用户的客户信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 客户信息分页列表
     */
    @Override
    public TableDataInfo<CustomerVo> queryPageMyCustomerList(CustomerBo bo, PageQuery pageQuery) {
        // 获取当前登录用户的公司ID
        EmployeeVo employeeVo = employeeService.queryById(bo.getCompanyId());
        bo.setCompanyId(employeeVo.getCompanyId());
        MPJLambdaWrapper<Customer> mpjWrapper = getCustomerInfoByJoinTable(bo);
        Page<CustomerVo> result = baseMapper.selectJoinPage(pageQuery.build(), CustomerVo.class, mpjWrapper);
        return TableDataInfo.build(result);
    }

    /**
     * 联表查询customer、company和employee表
     */
    private static MPJLambdaWrapper<Customer> getCustomerInfoByJoinTable(CustomerBo bo) {
        // 使用MPJBaseMapper进行联表查询customer、company和employee表
        MPJLambdaWrapper<Customer> mpjWrapper = new MPJLambdaWrapper<Customer>()
            .selectAll(Customer.class)
            .selectAssociation(Company.class, CustomerVo::getCompanyInfo)
            .selectAssociation(Employee.class, CustomerVo::getEmployeeInfo)
            .leftJoin(Company.class, Company::getId, Customer::getCompanyId)
            .leftJoin(Employee.class, Employee::getId, Customer::getCreatorId)
            .orderByDesc(Customer::getCreateTime)
            .eq(bo.getCompanyId() != null, Customer::getCompanyId, bo.getCompanyId())
            .eq(bo.getCreatorId() != null, Customer::getCreatorId, bo.getCreatorId())
            .like(StringUtils.isNotBlank(bo.getCustomerName()), Customer::getCustomerName, bo.getCustomerName())
            .like(StringUtils.isNotBlank(bo.getContactPerson()), Customer::getContactPerson, bo.getContactPerson())
            .like(StringUtils.isNotBlank(bo.getPhone()), Customer::getPhone, bo.getPhone())
            .like(StringUtils.isNotBlank(bo.getProvince()), Customer::getProvince, bo.getProvince())
            .like(StringUtils.isNotBlank(bo.getCity()), Customer::getCity, bo.getCity())
            .like(StringUtils.isNotBlank(bo.getDistrict()), Customer::getDistrict, bo.getDistrict())
            .like(StringUtils.isNotBlank(bo.getDetailAddress()), Customer::getDetailAddress, bo.getDetailAddress())
            .like(StringUtils.isNotBlank(bo.getRemark()), Customer::getRemark, bo.getRemark());
        return mpjWrapper;
    }

    /**
     * 查询符合条件的客户信息列表
     *
     * @param bo 查询条件
     * @return 客户信息列表
     */
    @Override
    public List<CustomerVo> queryList(CustomerBo bo) {
        LambdaQueryWrapper<Customer> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Customer> buildQueryWrapper(CustomerBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Customer> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(Customer::getCreateTime);
        lqw.eq(bo.getCompanyId() != null, Customer::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getCreatorId() != null, Customer::getCreatorId, bo.getCreatorId());
        lqw.like(StringUtils.isNotBlank(bo.getCustomerName()), Customer::getCustomerName, bo.getCustomerName());
        lqw.like(StringUtils.isNotBlank(bo.getContactPerson()), Customer::getContactPerson, bo.getContactPerson());
        lqw.like(StringUtils.isNotBlank(bo.getPhone()), Customer::getPhone, bo.getPhone());
        lqw.like(StringUtils.isNotBlank(bo.getProvince()), Customer::getProvince, bo.getProvince());
        lqw.like(StringUtils.isNotBlank(bo.getCity()), Customer::getCity, bo.getCity());
        lqw.like(StringUtils.isNotBlank(bo.getDistrict()), Customer::getDistrict, bo.getDistrict());
        lqw.like(StringUtils.isNotBlank(bo.getDetailAddress()), Customer::getDetailAddress, bo.getDetailAddress());
        lqw.like(StringUtils.isNotBlank(bo.getRemark()), Customer::getRemark, bo.getRemark());
        return lqw;
    }

    /**
     * 新增客户信息
     *
     * @param bo 客户信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(CustomerBo bo) {
        Customer add = MapstructUtils.convert(bo, Customer.class);
        EmployeeVo employeeVo = employeeService.queryById(add.getCreatorId());
        add.setCompanyId(employeeVo.getCompanyId());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改客户信息
     *
     * @param bo 客户信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(CustomerBo bo) {
        Customer update = MapstructUtils.convert(bo, Customer.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Customer entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除客户信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 根据主体公司id查询所属的客户数量
     *
     * @param companyId 主体ID
     * @return 客户数量
     */
    @Override
    public Long queryCustomerTotalByCompanyId(Long companyId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<Customer>().eq(Customer::getCompanyId, companyId));
    }
}
